use std::{fs, path::PathBuf};
use tauri::{path::BaseDirectory, AppHandle, Error, Manager};
use tauri_plugin_shell::{process, ShellExt};

use crate::model::Command;

pub fn get_config_file(app: &AppHandle) -> Result<PathBuf, Error> {
    let name = app.package_info().name.as_str();
    let path = app
        .path()
        .resolve(format!("{}/config.yaml", name), BaseDirectory::Config)
        .unwrap();

    let dir = path.parent().unwrap().to_path_buf();
    if !dir.exists() {
        fs::create_dir_all(dir).unwrap();
    }

    Ok(path)
}

pub fn get_service_shell(cmd: &Command, app: &AppHandle) -> Option<process::Command> {
    let shell = app.shell().sidecar("service").map_err(|e| e.to_string());

    let shell = match shell {
        Ok(v) => v,
        Err(_) => return None,
    };

    let mut args = vec![];

    match cmd {
        Command::Web => args.push("web"),
        Command::Cron => args.push("cron"),
        Command::Vista => args.push("vista"),
        Command::Lab => args.push("lab"),
    };

    let conf = get_config_file(app).unwrap();
    let conf = match conf.to_str() {
        Some(conf) => conf,
        None => "",
    };
    args.push("--config");
    args.push(conf);

    Some(shell.args(args))
}
